// app.js

const express = require('express');
const mysql = require('mysql');

const app = express();
const port = 3000;

// 创建数据库连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database'
});

// 解析 JSON 请求体
app.use(express.json());

// 递归构建树结构
function buildTree(comments, parentId = null) {
    const tree = [];
    for (const comment of comments) {
        if (comment.parent_comment_id === parentId) {
            const children = buildTree(comments, comment.comment_id);
            if (children.length) {
                comment.children = children;
            }
            tree.push(comment);
        }
    }
    return tree;
}

// 查询文章及其评论的通用函数
function getArticlesAndComments(articleId, callback) {
    const articlesSql = `
    SELECT
        id AS article_id,
        title AS article_title,
        content AS article_content,
        image_url AS article_image_url,
        created_at AS article_created_at,
        updated_at AS article_updated_at,
        published_at AS article_published_at,
        ip_address AS article_ip_address,
        likes AS article_likes
    FROM
        Articles
    ${articleId ? 'WHERE id = ?' : ''}
  `;

    const commentsSql = `
    SELECT
        c.id AS comment_id,
        c.content AS comment_content,
        c.created_at AS comment_created_at,
        c.likes AS comment_likes,
        cu.username AS comment_author_username,
        cu.email AS comment_author_email,
        c.parent_comment_id,
        c.article_id
    FROM
        Comments c
    JOIN
        Users cu ON c.author_id = cu.id
    ${articleId ? 'WHERE c.article_id = ?' : ''}
    ORDER BY
        c.created_at ASC;
  `;

    // 查询文章
    pool.query(articlesSql, articleId ? [articleId] : [], (error, articlesResults) => {
        if (error) {
            return callback(error);
        }

        // 查询评论
        pool.query(commentsSql, articleId ? [articleId] : [], (error, commentsResults) => {
            if (error) {
                return callback(error);
            }

            // 构建树结构
            if (articleId) {
                const article = articlesResults[0];
                article.comments = buildTree(commentsResults, null);
                callback(null, article);
            } else {
                const articles = articlesResults.map(article => {
                    article.comments = buildTree(commentsResults.filter(comment => comment.article_id === article.article_id), null);
                    return article;
                });
                callback(null, articles);
            }
        });
    });
}

// 根据文章 ID 获取文章及其评论
app.get('/article/:id', (req, res) => {
    const articleId = req.params.id;

    getArticlesAndComments(articleId, (error, result) => {
        if (error) {
            console.error('Error fetching data:', error);
            res.status(500).json({error: 'Error fetching data'});
        } else if (!result) {
            res.status(404).json({error: 'Article not found'});
        } else {
            res.json(result);
        }
    });
});

// 获取所有文章及其评论
app.get('/articles', (req, res) => {
    getArticlesAndComments(null, (error, result) => {
        if (error) {
            console.error('Error fetching data:', error);
            res.status(500).json({error: 'Error fetching data'});
        } else {
            res.json(result);
        }
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});